package com.panicstyle.Gongdong;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.http.NameValuePair;
import org.apache.http.client.CookieStore;
import org.apache.http.client.HttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HttpContext;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.Menu;
import android.view.MenuItem;
import android.webkit.WebView;

public class ArticleView extends Activity implements Runnable {
	/** Called when the activity is first created. */
	protected HttpClient httpClient;
	protected HttpContext httpContext;
    private ProgressDialog pd;
    String mhtmlDoc;
    String mContent;
    String mComment;
    static final int REQUEST_WRITE = 1;
    static final int REQUEST_MODIFY = 2;
    static final int REQUEST_COMMENT_WRITE = 3;
    static final int REQUEST_COMMENT_MODIFY = 4;
    static final int REQUEST_COMMENT_REPLY_VIEW = 5;
    static final int REQUEST_COMMENT_MODIFY_VIEW = 6;
    static final int REQUEST_COMMENT_DELETE_VIEW = 7;
    String mCommID;
    String mBoardID;
    String mBoardNo;
    String mCommentNo;
    protected int mLoginStatus;
    
	String g_isPNotice;
	String g_isNotice;
	String g_Subject;
	String g_UserName;
	String g_UserID;
	String g_Date;
	String g_Link;
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        GongdongApplication app = (GongdongApplication)getApplication();
        httpClient = app.httpClient;
        httpContext = app.httpContext;
        
        intenter();
        
        LoadData();
    }
    
    public void LoadData() {
        pd = ProgressDialog.show(this, "", "로딩중입니다. 잠시만 기다리십시오...", true, false);

        Thread thread = new Thread(this);
        thread.start();

        return;
    }

    public void run() {
    	if (!getData(httpClient, httpContext)) {
            // Login
    		Login login = new Login();
    		
    		mLoginStatus = login.LoginTo(httpClient, httpContext, ArticleView.this);
    		
    		if (mLoginStatus > 0) {
    			if (getData(httpClient, httpContext)) {
    				mLoginStatus = 1;
    			} else {
    				mLoginStatus = -2;
    			}
    		}
    	} else {
			mLoginStatus = 1;
    	}
    	handler.sendEmptyMessage(0);
    }

    private Handler handler = new Handler() {
    	@Override
    	public void handleMessage(Message msg) {
    		pd.dismiss();
    		displayData();
    	}
    };        
    
    public void displayData() {
		if (mLoginStatus == -1) {
			AlertDialog.Builder ab = null;
			ab = new AlertDialog.Builder( this );
			ab.setMessage( "로그인 정보가 설정되지 않았습니다. 설정 메뉴를 통해 로그인 정보를 설정하십시오.");
			ab.setPositiveButton(android.R.string.ok, null);
			ab.setTitle( "로그인 오류" );
			ab.show();
		} else if (mLoginStatus == -2){
			AlertDialog.Builder ab = null;
			ab = new AlertDialog.Builder( this );
			ab.setMessage( "게시판을 볼 권한이 없습니다.");
			ab.setPositiveButton(android.R.string.ok, null);
			ab.setTitle( "권한 오류" );
			ab.show();
		} else if (mLoginStatus == 0){
			AlertDialog.Builder ab = null;
			ab = new AlertDialog.Builder( this );
			ab.setMessage( "로그인을 실패했습니다 설정 메뉴를 통해 로그인 정보를 변경하십시오.");
			ab.setPositiveButton(android.R.string.ok, null);
			ab.setTitle( "로그인 오류" );
			ab.show();
		} else {
			WebView webview = new WebView(this);
			webview.getSettings().setJavaScriptEnabled(true);
			setContentView(webview);
			String baseURL = "http://cafe.gongdong.or.kr";
			webview.loadDataWithBaseURL(baseURL, mhtmlDoc, "text/html", "utf-8", "");
		}
    }
    
    public void intenter() {
//    	Intent intent = getIntent();  // 값을 가져오는 인텐트 객체생성
    	Bundle extras = getIntent().getExtras();
    	// 가져온 값을 set해주는 부분
    	g_isPNotice = extras.getString("ISNOTICE").toString();
    	g_isNotice = extras.getString("ISNOTICE").toString();
    	g_Subject = extras.getString("SUBJECT").toString();
    	g_UserName = extras.getString("USERNAME").toString();
    	g_UserID = extras.getString("USERID").toString();
    	g_Date = extras.getString("DATE").toString();
    	g_Link = extras.getString("LINK").toString();
    	
        Pattern p = Pattern.compile("(?<=p1=)(.|\\n)*?(?=&)", Pattern.CASE_INSENSITIVE); 
        Matcher m = p.matcher(g_Link);
        if (m.find()) { // Find each match in turn; String can't do this.     
//        	items.add(m.group(0)); // Access a submatch group; String can't do this. }
        	mCommID = m.group(0);
        } else {
        	mCommID = "";
        }
    
        p = Pattern.compile("(?<=sort=)(.|\\n)*?(?=&)", Pattern.CASE_INSENSITIVE); 
        m = p.matcher(g_Link);
        if (m.find()) { // Find each match in turn; String can't do this.     
//        	items.add(m.group(0)); // Access a submatch group; String can't do this. }
        	mBoardID = m.group(0);
        } else {
        	mBoardID = "";
        }
    	
        p = Pattern.compile("(?<=number=)(.|\\n)*?(?=&)", Pattern.CASE_INSENSITIVE); 
        m = p.matcher(g_Link);
        if (m.find()) { // Find each match in turn; String can't do this.     
//        	items.add(m.group(0)); // Access a submatch group; String can't do this. }
        	mBoardNo = m.group(0);
        } else {
        	mBoardNo = "";
        }
    }

    protected boolean getData(HttpClient httpClient, HttpContext httpContext) {		
		
		String url = "http://cafe.gongdong.or.kr" + g_Link;
		HttpRequest httpRequest = new HttpRequest();
        String result = httpRequest.requestGet(httpClient, httpContext, url, "", "utf-8");
        
        if (result.length() < 200) {
        	return false;
        }

        String strTitle = "<div align='left'>" + g_Subject + "</div><br /><div align='right'>" + g_UserName + " [" + g_Date + "]</div><hr>";
        
        Pattern p = Pattern.compile("(?<=<!---- contents start 본문 표시 부분 DJ ---->)(.|\\n)*?(?=<!---- contents end ---->)", Pattern.CASE_INSENSITIVE); 
        Matcher m = p.matcher(result);
        
        if (m.find()) { // Find each match in turn; String can't do this.     
        	mContent = m.group(0);
        } else {
        	mContent = "";
        }

        p = Pattern.compile("(<p align=center><img onload=\\\"resizeImage2[(]this[)]\\\")(.|\\n)*?(?=</td>)", Pattern.CASE_INSENSITIVE); 
        m = p.matcher(result);
        
        String strImage;
        if (m.find()) { // Find each match in turn; String can't do this.     
        	strImage = m.group(0);
        } else {
        	strImage = "";
        }
        
        p = Pattern.compile("(?<=<!-- 댓글 시작 -->)(.|\\n)*?(?=<!-- 댓글 끝 -->)", Pattern.CASE_INSENSITIVE); 
        m = p.matcher(result);
        
        if (m.find()) { // Find each match in turn; String can't do this.     
        	mComment = m.group(0);
        } else {
        	mComment = "";
        }
        
        mComment = mComment.replaceAll("<IMG src=\"images/b_edit.gif\" border=0 hspace=\"0\" alt=\"삭제하기\" align=absmiddle>", "");
        mComment = mComment.replaceAll("<IMG src=\"images/b_del.gif\" border=0 hspace=\"0\" alt=\"삭제하기\" align=absmiddle>", "");
        mComment = mComment.replaceAll("<IMG src=\"images/bt_reply.gif\" border=0 hspace=\"0\" alt=\"댓글쓰기\" align=absmiddle>", "");
        mComment = mComment.replaceAll("href=\"javascript:ui", "");
        mComment = mComment.replaceAll("href=\"JavaScript:self.location=", "");

//        String strHeader = "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">";
        String strHeader = "<html><head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\">";
        strHeader += "<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0, user-scalable=no, target-densitydpi=medium-dpi\">";
        strHeader += "</head><body>";
        String strResize = "<script>function resizeImage2(mm){var width = eval(mm.width);var height = eval(mm.height);if( width > 300 ){var p_height = 300 / width;var new_height = height * p_height;eval(mm.width = 300);eval(mm.height = new_height);}} function image_open(src, mm) {var src1 = 'image2.php?imgsrc='+src;window.open(src1,'image','width=1,height=1,scrollbars=yes,resizable=yes');}</script>";
        String strBottom = "</body></html>";

    	mhtmlDoc = strHeader + strTitle + strResize + mContent + strImage + mComment + strBottom;

        return true;
    }

    @Override  
    public boolean onCreateOptionsMenu(Menu menu) {  
        super.onCreateOptionsMenu(menu);  
          
        menu.add(0, 0, 0, "글답변");  
        menu.add(0, 1, 0, "글수정");
        menu.add(0, 2, 0, "글삭제");  
        menu.add(0, 3, 0, "댓글쓰기");  
        menu.add(0, 4, 0, "답변댓글쓰기");  
        menu.add(0, 5, 0, "댓글수정");  
        menu.add(0, 6, 0, "댓글삭제");  
          
        return true;  
    }  
      
    @Override  
    public boolean onOptionsItemSelected(MenuItem item) {  
        
    	if (item.getItemId() == 0) {	// 글답변
            Intent intent = new Intent(this, ArticleWrite.class);
	        intent.putExtra("COMMID", mCommID);
	        intent.putExtra("BOARDID", mBoardID);
	        intent.putExtra("BOARDNO",  mBoardNo);
            startActivityForResult(intent, REQUEST_WRITE);
    	} else if (item.getItemId() == 1) {	// 글수정
            Intent intent = new Intent(this, ArticleModify.class);
	        intent.putExtra("COMMID", mCommID);
	        intent.putExtra("BOARDID", mBoardID);
	        intent.putExtra("BOARDNO", mBoardNo);
	        intent.putExtra("TITLE",  g_Subject);
	        intent.putExtra("CONTENT", mContent);
            startActivityForResult(intent, REQUEST_MODIFY);
            return true;  
    	} else if (item.getItemId() == 2) {	// 글삭제
    		DeleteArticleConfirm();
    	} else if (item.getItemId() == 3) {	// 댓글쓰기
            Intent intent = new Intent(this, CommentWrite.class);
	        intent.putExtra("COMMID", mCommID);
	        intent.putExtra("BOARDID", mBoardID);
	        intent.putExtra("BOARDNO",  mBoardNo);
	        intent.putExtra("COMMENTNO",  "");
            startActivityForResult(intent, REQUEST_COMMENT_WRITE);
    	} else if (item.getItemId() == 4) {	// 답변댓글쓰기
            Intent intent = new Intent(this, CommentView.class);
	        intent.putExtra("CONTENT", mComment);
	        intent.putExtra("MODE", "REPLY");
            startActivityForResult(intent, REQUEST_COMMENT_REPLY_VIEW);
    	} else if (item.getItemId() == 5) {	// 댓글수정
            Intent intent = new Intent(this, CommentView.class);
	        intent.putExtra("CONTENT", mComment);
	        intent.putExtra("MODE", "");
            startActivityForResult(intent, REQUEST_COMMENT_MODIFY_VIEW);
    	} else if (item.getItemId() == 6) {	// 댓글삭제
            Intent intent = new Intent(this, CommentView.class);
	        intent.putExtra("CONTENT", mComment);
	        intent.putExtra("MODE", "");
            startActivityForResult(intent, REQUEST_COMMENT_DELETE_VIEW);
    	}   
        return false;  
    }
    
    protected void DeleteArticleConfirm() {
		AlertDialog.Builder ab = null;
		ab = new AlertDialog.Builder( this );
		ab.setMessage( "정말 삭제하시겠습니까?");
		ab.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int whichButton) {
				DeleteArticle();
			}
		});
		ab.setNegativeButton(android.R.string.cancel, null);
		ab.setTitle( "확인" );
		ab.show();
		return;    	
    }
    
    protected void DeleteArticle() {
		HttpRequest httpRequest = new HttpRequest();
		
		String url = "http://cafe.gongdong.or.kr/cafe.php?mode=del&sort=" + mBoardID + "&sub_sort=&p1=" + mCommID + "&p2=";
		String referer = "http://121.134.211.159/board-edit.do";
		
		ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
		nameValuePairs.add(new BasicNameValuePair("number", mBoardNo));
		nameValuePairs.add(new BasicNameValuePair("passwd", ""));

		String result = httpRequest.requestPost(httpClient, httpContext, url, nameValuePairs, referer, "utf-8");
		
        if (result.indexOf("<meta http-equiv=\"refresh\" content=\"0;url=/cafe.php?sort=") < 0) {
            Pattern p = Pattern.compile("(?<=window.alert\\(\\\")(.|\\n)*?(?=\\\")", Pattern.CASE_INSENSITIVE); 
            Matcher m = p.matcher(result);
            
            String strErrorMsg;
            if (m.find()) { // Find each match in turn; String can't do this.     
            	strErrorMsg = m.group(0);
            } else {
            	strErrorMsg = "";
            }
    		AlertDialog.Builder ab = null;
			ab = new AlertDialog.Builder( this );
			strErrorMsg = "글 삭제중 오류가 발생했습니다. \n" + strErrorMsg; 
			ab.setMessage(strErrorMsg);
			ab.setPositiveButton(android.R.string.ok, null);
			ab.setTitle( "확인" );
			ab.show();
			return;
        }
        if (getParent() == null) {
           	setResult(Activity.RESULT_OK, new Intent());
        } else {
        	getParent().setResult(Activity.RESULT_OK, new Intent());
        }
        finish();
    }
    
    protected void ModifyComment() {
        Intent intent = new Intent(this, CommentModify.class);
        intent.putExtra("COMMID", mCommID);
        intent.putExtra("BOARDID", mBoardID);
        intent.putExtra("BOARDNO",  mBoardNo);
        intent.putExtra("COMMENTNO",  mCommentNo);
        intent.putExtra("COMMENT",  mComment);
        
        startActivityForResult(intent, REQUEST_COMMENT_MODIFY);
    }
    
    protected void DeleteCommentConfirm() {
		AlertDialog.Builder ab = null;
		ab = new AlertDialog.Builder( this );
		ab.setMessage( "정말 삭제하시겠습니까?");
		ab.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int whichButton) {
				DeleteComment();
			}
		});
		ab.setNegativeButton(android.R.string.cancel, null);
		ab.setTitle( "확인" );
		ab.show();
		return;    	
    }
    
    protected void DeleteComment() {
		HttpRequest httpRequest = new HttpRequest();
		
		String url = "http://cafe.gongdong.or.kr/cafe.php?mode=del_reply&sort=" + mBoardID + "&sub_sort=&p1=" + mCommID + "&p2=";
		String referer = "http://121.134.211.159/board-edit.do";
		
		ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
		nameValuePairs.add(new BasicNameValuePair("number", mCommentNo));

		String result = httpRequest.requestPost(httpClient, httpContext, url, nameValuePairs, referer, "utf-8");
		
        if (result.indexOf("<meta http-equiv=\"refresh\" content=\"0;url=/cafe.php?sort=") < 0) {
            Pattern p = Pattern.compile("(?<=window.alert\\(\\\")(.|\\n)*?(?=\\\")", Pattern.CASE_INSENSITIVE); 
            Matcher m = p.matcher(result);
            
            String strErrorMsg;
            if (m.find()) { // Find each match in turn; String can't do this.     
            	strErrorMsg = m.group(0);
            } else {
            	strErrorMsg = "";
            }
    		AlertDialog.Builder ab = null;
			ab = new AlertDialog.Builder( this );
			strErrorMsg = "글 삭제중 오류가 발생했습니다. \n" + strErrorMsg; 
			ab.setMessage(strErrorMsg);
			ab.setPositiveButton(android.R.string.ok, null);
			ab.setTitle( "확인" );
			ab.show();
			return;
        }
        LoadData();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
    	super.onActivityResult(requestCode, resultCode, intent);
    	Bundle extras;
    	String strCommentNo;
    	Intent newIntent;
    	switch(requestCode) {
    	case REQUEST_WRITE:
    	case REQUEST_MODIFY:
    	case REQUEST_COMMENT_WRITE:
    	case REQUEST_COMMENT_MODIFY:
    		if (resultCode == RESULT_OK) {
    			
    	        pd = ProgressDialog.show(this, "", "로딩중입니다. 잠시만 기다리십시오...", true, false);

    	        Thread thread = new Thread(this);
    	        thread.start();    		
    	    }
    		break;
    	case REQUEST_COMMENT_REPLY_VIEW:
    		if (resultCode == RESULT_OK) {
	        	// 가져온 값을 set해주는 부분
    			extras = intent.getExtras();
    			strCommentNo = extras.getString("COMMENTNO").toString();
	
	        	newIntent = new Intent(this, CommentWrite.class);
		        newIntent.putExtra("COMMID", mCommID);
		        newIntent.putExtra("BOARDID", mBoardID);
		        newIntent.putExtra("BOARDNO", mBoardNo);
		        newIntent.putExtra("COMMENTNO", strCommentNo);
		        startActivityForResult(newIntent, REQUEST_COMMENT_WRITE);
    		}
    		break;
    	case REQUEST_COMMENT_MODIFY_VIEW:
    		if (resultCode == RESULT_OK) {
	        	// 가져온 값을 set해주는 부분
    			extras = intent.getExtras();
	        	mCommentNo = extras.getString("COMMENTNO").toString();
	        	mComment = extras.getString("COMMENT").toString();
	        	ModifyComment();
    		}
    		break;
    	case REQUEST_COMMENT_DELETE_VIEW:
    		if (resultCode == RESULT_OK) {	// resultCode 가 항상 0 으로 넘어옴. 해결책 못 찾음. 일단 SetView 가 실행되면 다시 로딩하자.
	        	// 가져온 값을 set해주는 부분
    			extras = intent.getExtras();
	        	mCommentNo = extras.getString("COMMENTNO").toString();
	        	DeleteCommentConfirm();
    		}
    		break;
    	}
    }
}
